<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Session;
use think\Request;


class Index extends Controller
{   
    //加载登陆页面
    public function index()
    {
        return view('index/index');
    }

    public function doadmin()
    {
        $username=$_POST['username'];
        $password=MD5($_POST['password']);

        $list=Db::name('user')->where('username="'.$username.'"and userpass="'.$password.'"')->find();
        if (!empty($list)) {
            
            Session::set('name',$list['username']);
            Session::set('id',$list['id']);
            $id =  Session::get('id');
            $list = Db::view('node','mname,aname')
            ->view('role_node','nid','node.id=role_node.nid and node.status=1')
            ->view('user_role','rid','role_node.rid=user_role.rid')
            ->view('user','id','user.id=user_role.uid')
            ->where('id','=',$id)->select();
            
            

            foreach ($list as $key => $val) {
                $list[$key]['mname'] = ucfirst($val['mname']);
            }

            $nodelist = array();
            foreach($list as $v){
                $nodelist[$v['mname']][] = $v['aname'];
            }

            Session::set('qx',$nodelist);

            // var_dump($nodelist);die;

            return $this->success('成功',url('admin/user/index'));
        }else{
            return $this->error('请先登录',url('admin/index/index'));
        }
    }

    // 退出登陆清除session
    public function outlogin()
    {    
        
        $sql=Db::name('');
        Session::delete('qx');
        Session::delete('name');
        return $this->success('成功',url('admin/index/index'));
    }

    //注册管理员
    public function register()
    {

        return view('index/register');
    }

    //添加管理员  
    public function doregister(Request $request)
    {   
        $req = $request->post();
        if ($req['password']==$req['rpassword']) {
            $req['rpassword']='';
        }else{
            return $this->error('密码不相同',url('index/register'));
        }
        
        $cd=db('user')->select();
        
        foreach ($cd as $k => $v) {
            if ($v['username']==$req['uname']) {
                return $this->error('已注册',url('index/register'));
            }
        }
        // var_dump($req);
        // die;
        $req['password']=md5($req['password']);

        $data = ['username' => $req['uname'], 'name' => $req['name'],'userpass' => $req['password'] ];

        Db::name('user')->insert($data);
        $id = Db::name('user')->getLastInsID();

        $t=['uid'=>$id,'rid'=>'7'];
        $sql=Db::name('user_role')->insert($t);


        

        return $this->success('注册成功',url('admin/index/index'));
    }

}

